package com.yaodian100.mall.member.web;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.geronimo.mail.util.Base64;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.xml.sax.SAXException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.qq.connect.AccessToken;
import com.qq.connect.InfoToken;
import com.qq.connect.RequestToken;
import com.qq.util.ParseString;
import com.qq.util.Verify;
import com.qq.util.XMLHelper;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.exception.CoreException;
import com.yaodian100.core.common.utils.BytesUtil;
import com.yaodian100.core.common.utils.CryptoUtil;
import com.yaodian100.core.common.utils.PasswordUtils;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.entity.Menu;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.core.template.service.TemplateService;
import com.yaodian100.crm.activities.entity.MgmCoupon;
import com.yaodian100.crm.activities.service.MgmService;
import com.yaodian100.crm.cs.service.CsService;
import com.yaodian100.ec.announcement.entity.Announcement;
import com.yaodian100.ec.announcement.service.AnnouncementService;
import com.yaodian100.ec.channel.service.ChannelService;
import com.yaodian100.ec.coupon.entity.CouponItem;
import com.yaodian100.ec.coupon.service.CouponService;
import com.yaodian100.ec.member.entity.AddressBook;
import com.yaodian100.ec.member.entity.ImageValid;
import com.yaodian100.ec.member.entity.LoginHistory;
import com.yaodian100.ec.member.entity.Member;
import com.yaodian100.ec.member.entity.ViewWishList;
import com.yaodian100.ec.member.service.MemberService;
import com.yaodian100.ec.member.service.impl.XunLeiServiceImpl;
import com.yaodian100.ec.memberevent.entity.MemberEvent;
import com.yaodian100.ec.memberevent.entity.MemberGift;
import com.yaodian100.ec.product.entity.Product;
import com.yaodian100.ec.product.entity.Specification;
import com.yaodian100.ec.product.service.OrderCommentService;
import com.yaodian100.ec.product.service.ProductService;
import com.yaodian100.ec.shopping.entity.CartOrderProduct;
import com.yaodian100.ec.shopping.entity.CartOrderProductDetail;
import com.yaodian100.ec.shopping.entity.CartOrders;
import com.yaodian100.ec.shopping.service.CartOrdersService;
import com.yaodian100.mall.member.util.UserData;
import com.yaodian100.sina.weibo4j.User;

/**
 * 
 * @author apple.chang
 * 
 */
public class MemberAction extends ActionSupport {

	private ProductService productService;
	@Autowired
	private MgmService mgmService;
	@Autowired
	private CouponService couponService;

	protected final Logger logger = LoggerFactory.getLogger(getClass());

	private static final long serialVersionUID = 1L;
	private static final int LOGINERROR_TIMES = 10;
	private static final String XUNLEI_MEMBER = "xunleimember";
	@Resource
	private CartOrdersService cartOrdersService;
	private MemberService memberService;
	private ChannelService channelService;
	@Autowired
	private XunLeiServiceImpl xunLeiServiceImpl;
	@Autowired
	private MenuService menuService;
	@Autowired
	private CsService csService;
	@Resource
	private TemplateService velocityService;
	@Resource
	private OrderCommentService orderCommentService;
	private List<AddressBook> abList;
	private List<ViewWishList> viewWishList;
	private AnnouncementService announcementService;
	private List<Announcement> annList;
	private List<Announcement> memberMessageList;
	private Member member;
	private String loginID;
	private String memberId;
	private String xloginID;
	private String nickId;
	private String mail;
	private String opwd;
	private String remember;
	private String pwd;
	private String rcpwd;
	private String ccode;
	private String from;
	private String regresult;
	private String loginresult;
	private String modifyPwdResult;
	private String pathparam;
	private String actionResult;
	private String abId;
	private String contactName;
	private String province;
	private String city;
	private String district;
	private String zipCode;
	private String addr;
	private String mobile;
	private String areaCode;
	private String phone;
	private String extension;
	private String redirect_url;
	private String url;
	private String site;
	private String edm;
	private String sms;
	private String yid;
	private int errTimes;
	private int xerrTimes;
	private String mgmName;
	private CouponItem cpItem;

	private String sex;
	private String birthday;

	private String code; // activate code
	private Date canModifyDate;
	private MemberGift memberGift;
	private MemberEvent memberEvent;
	private Product product;
	private Specification spec;

	// redirect cookie
	private String a_id;
	private String m_id;
	private String c_id;
	private String l_id;
	private String l_type1;
	private String rd;
	private String wid;
	private String fbt;
	private String u_id;

	private final String qqFanliKey1 = "ldiou37d6$%#(*&Doe8eld(89jeld[pleeOIU^783uI*u";
	private final String qqFanliKey2 = "(*DOjkkdwe[pleU^7diou37d6$%#HYuOIing6$%#0jdli";
	private String qqName;
	private String fanliKey = "51fanliyaodian100";

	private static final String PCLADY_APP_KEY = "yaodian100_app";
	private static final String PCLADY_SECRET = "F565F2028E8FD1280027E847713FE50C";

	private final String limitMobileRegTimes = "3";

	private String showMsg;
	private String completeInfoBonus;

	private String numOrderCommet = "0";

	// private UserData userData;

	// public UserData getUserData() {
	// return userData;
	// }
	//
	// public void setUserData(UserData userData) {
	// this.userData = userData;
	// }

	/**
	 * 激活信箱 - 確認更新
	 * 
	 * @return
	 * @throws Exception
	 */
	public String activateModifyEmail() throws Exception {
		if (StringUtils.isBlank(memberService.get(UserLoginData.getMemberId()).getEmail())) {
			actionResult = "new_email";
		}
		member = memberService.updateMemberEmail(UserLoginData.getMemberId());
		if (null == member) {
			return "activateEmailExist";
		}
		mail = member.getEmail();
		return "activateEmailSuccess";
	}

	private boolean checkCode(String imageId, String inputCode) {
		ImageValid imageValid = new ImageValid();
		imageValid.setId(imageId);
		imageValid.setValidData(inputCode);
		try {
			memberService.isImageValid(imageValid);
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private void checkGift(Member member) {
		memberEvent = memberService.getMemberEvent(member);
		memberGift = memberService.getMemberGift(member);
		if (null != memberGift && !memberGift.getType().equals("3")) {
			product = productService.get(memberGift.getContent());
			if (null == product) {
				memberGift = null;
				return;
			}
			CommonCriteria criteria = new CommonCriteria();
			criteria.addEq("productId", memberGift.getContent());
			spec = productService.getSpecificationList(0, -1, criteria, null).get(0);
		}
	}

	/**
	 * 
	 * 
	 * @return
	 * @throws Exception
	 */
	public String checkLogin() throws Exception {
		if (isLogin()) {
			actionResult = "login";
		} else {
			if (StringUtils.contains(pathparam, "/reloadCart.do")) {
				pathparam = ServerValue.getFrontHostname() + ServerValue.getFrontContextPath() + "/shopping/cart.do";
			} else if (!(StringUtils.contains(pathparam, "/category/") || StringUtils.contains(pathparam, "/product/")
					|| StringUtils.contains(pathparam, "/help/") || StringUtils.contains(pathparam, "/act/")
					|| StringUtils.contains(pathparam, "/info/") || StringUtils.contains(pathparam, "/tuangou/"))) {
				pathparam = ServerValue.getFrontHostname() + "/";
			}
			actionResult = URLEncoder.encode(pathparam, "utf-8");
		}
		return "checked";
	}

	/**
	 * 刪除地址簿
	 * 
	 * @return
	 * @throws Exception
	 */
	public String deleteAddressBook() throws Exception {
		if (memberService.deleteAddressBook(Long.parseLong(abId))) {
			actionResult = "success";
		} else {
			actionResult = "error";
		}
		return "jsonSaveAddressBook";
	}

	/**
	 * 切换到删除手机页 (2011.09.30 移除此功能)
	 * 
	 * @return
	 */
	public String deletemobile() {
		return modifydata();
	}

	/**
	 * 验证效验码&删除手机
	 * 
	 * @return
	 */
	public String deleteMobileActivate() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		if (!ccode.equalsIgnoreCase(member.getActivateMobileToken())) {
			actionResult = "ccode_error";
			return "deletemobilecheck";
		}
		memberService.deleteMobile(member);
		return "deletemobileok";
	}

	/**
	 * 验证校验码 - 删除手机
	 * 
	 * @return
	 */
	public String deletemobilecheck() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		if (StringUtils.isBlank(ccode)) {
			ccode = "error";
			return "not_match";
		}
		if (!PasswordUtils.decodePassword(ccode, null).equals(member.getLoginId())) {
			return "not_match"; // 登入帳戶與激活連結的loginId不一致
		}
		if (StringUtils.isBlank(member.getActivateMobileToken())) {
			ccode = "error";
			return "not_match";
		}
		actionResult = "login_ok";
		return "deletemobilecheck";
	}

	/**
	 * 切换到忘记密码页
	 * 
	 * @return
	 */
	public String forgetpwd() {
		return "forgetpwd";
	}

	/**
	 * 切换到忘记密码-修改密码页
	 * 
	 * @return
	 */
	public String forgetpwdchange() {
		return "forgetpwdchange";
	}

	/**
	 * 忘记密码-執行修改密码
	 * 
	 * @return
	 */
	public String forgetpwdchanged() throws Exception {
		member = memberService.getMemberByLoginId(loginID);
		if (ccode.length() == 8) { // 手机找回
			if (!(StringUtils.isNotBlank(member.getActivateMobileToken()) && ccode.equalsIgnoreCase(member
					.getActivateMobileToken()))) {
				actionResult = "error";
				return "forgetpwdchange";
			}
		} else { // 邮箱找回
			if (!(StringUtils.isNotBlank(member.getForgetPwdToken()) && ccode.equals(member.getForgetPwdToken()))) {
				actionResult = "error";
				return "forgetpwdchange";
			}
		}
		memberService.updateMemberPwd(loginID, pwd);
		memberService.sendForgetPwdModifyOkMail(loginID, ccode);
		return "forgetpwdchanged";
	}

	/**
	 * 切换到忘记密码-修改密码页(手机找回)
	 * 
	 * @return
	 */
	public String forgetpwdmobilechange() {
		// 检查校验码
		member = memberService.getMemberByLoginId(loginID);
		mobile = member.getMobile();
		if (ccode.equalsIgnoreCase(member.getActivateMobileToken())) {
			return "forgetpwdchange";
		}
		actionResult = "code_error";
		return "forgetpwdmobilecheck";
	}

	/**
	 * 手机忘记密码邮件点回, 确认校验码
	 * 
	 * @return
	 */
	public String forgetpwdmobilecheck() {
		// 读出帐号
		loginID = PasswordUtils.decodePassword(loginID, null);
		member = memberService.getMemberByLoginId(loginID);
		mobile = member.getMobile();
		actionResult = "fromEmailLink";
		return "forgetpwdmobilecheck";
	}

	public String getA_id() {
		return a_id;
	}

	public String getAbId() {
		return abId;
	}

	public List<AddressBook> getAbList() {
		return abList;
	}

	public String getActionResult() {
		return actionResult;
	}

	public String getAddr() {
		return addr;
	}

	public List<Announcement> getAnnList() {
		return annList;
	}

	public AnnouncementService getAnnouncementService() {
		return announcementService;
	}

	public String getAreaCode() {
		return areaCode;
	}

	public String getC_id() {
		return c_id;
	}

	/**
	 * @return the canModifyDate
	 */
	public Date getCanModifyDate() {
		return canModifyDate;
	}

	public String getCcode() {
		return ccode;
	}

	public String getCity() {
		return city;
	}

	public String getCode() {
		return code;
	}

	public String getContactName() {
		return contactName;
	}

	public String getDistrict() {
		return district;
	}

	/**
	 * @return the edm
	 */
	public String getEdm() {
		return edm;
	}

	public String getExtension() {
		return extension;
	}

	public String getL_id() {
		return l_id;
	}

	public String getL_type1() {
		return l_type1;
	}

	public String getLoginID() {
		return loginID;
	}

	public String getLoginresult() {
		return loginresult;
	}

	public String getM_id() {
		return m_id;
	}

	public String getMail() {
		return mail;
	}

	public Member getMember() {
		return member;
	}

	public MemberEvent getMemberEvent() {
		return memberEvent;
	}

	public MemberGift getMemberGift() {
		return memberGift;
	}

	public MemberService getMemberService() {
		return memberService;
	}

	public String getMobile() {
		return mobile;
	}

	public String getModifyPwdResult() {
		return modifyPwdResult;
	}

	public String getNickId() {
		return nickId;
	}

	public String getOpwd() {
		return opwd;
	}

	public String getPathparam() {
		return pathparam;
	}

	public String getPathparamURLEncode() {
		try {
			return URLEncoder.encode(pathparam, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return "";
		}
	}

	public String getPhone() {
		return phone;
	}

	public Product getProduct() {
		return product;
	}

	public ProductService getProductService() {
		return productService;
	}

	public String getProvince() {
		return province;
	}

	public String getPwd() {
		return pwd;
	}

	public String getRcpwd() {
		return rcpwd;
	}

	public String getRd() {
		return rd;
	}

	public String getRegresult() {
		return regresult;
	}

	public String getRemember() {
		return remember;
	}

	/**
	 * @return the site
	 */
	public String getSite() {
		return site;
	}

	public Specification getSpec() {
		return spec;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	public List<ViewWishList> getViewWishList() {
		return viewWishList;
	}

	public String getZipCode() {
		return zipCode;
	}

	/**
	 * 执行删除手机号码
	 * 
	 * @return
	 */
	public String godeletemobile() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		actionResult = memberService.sendDeleteMobileActivateSms(member, pwd);
		if (actionResult.equals("pwd_error")) {
			return "deletemobile";
		}
		return "deletemobilecheck";
	}

	/**
	 * 忘記密碼 - 確認登入帳戶名後導到選擇修改密碼方式
	 * 
	 * @return
	 */
	public String goforgetpwd() {
		if (isNumeric(loginID) || loginID.length() > 20) {
			actionResult = "loginId_not_exist";
			return "forgetpwd";
		}
		member = memberService.getMemberByLoginId(loginID);
		if (null == member) {
			actionResult = "loginId_not_exist";
			return "forgetpwd";
		}
		member = memberService.checkMobileForgetPwdCount(member);
		return "forgetpwdway";
	}

	/**
	 * 忘記密碼 - 郵箱找回
	 * 
	 * @return
	 */
	public String goforgrtpwdemail() {
		return "goforgrtpwdemail";
	}

	/**
	 * 忘記密碼 - 手機找回
	 * 
	 * @return
	 */
	public String goforgrtpwdmobile() {
		return "goforgrtpwdmobile";
	}

	/**
	 * 执行修改E-mail
	 * 
	 * @return
	 * @throws Exception
	 */
	public String goModifyEmail() throws Exception {
		actionResult = memberService.sendModifyActivateMail(loginID, mail, pwd);
		member = memberService.getMemberByLoginId(loginID);
		if (actionResult.equals("pwd_error") || actionResult.equals("mail_exist")) {
			return "modifyemail";
		}
		return "modifyemailok";
	}

	/**
	 * 执行修改手机号码
	 * 
	 * @return
	 */
	public String gomodifymobile() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		if (ServerValue.getTrustMembers().contains(member.getApplySource())) {
			actionResult = memberService.sendModifyMobileActivateSms(member, mobile, pwd, false);
		} else {
			actionResult = memberService.sendModifyMobileActivateSms(member, mobile, pwd, StringUtils.isNotBlank(pwd));
		}
		if (actionResult.equals("pwd_error") || actionResult.equals("mobile_exist")) {
			if (StringUtils.isBlank(member.getMobile())) {
				return "newmobile";
			} else {
				return "modifymobile";
			}
		}
		return "modifymobilecheck";
	}

	/**
	 * save data
	 * 
	 * @return
	 * @throws Exception
	 */
	public String goreg() throws Exception {
		member = new Member();
		regresult = "";
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		member.setLoginId(loginID);

		if (StringUtils.isNotBlank(mobile)) {
			member.setMobile(mobile);
			member.setTempEmail(mail);
			if (StringUtils.isBlank(from)) {
				from = "mobile";
			}
		} else {
			member.setEmail(mail);
			if (StringUtils.isBlank(from)) {
				from = "mail";
			}
		}

		if (!checkCode(userData.getImageValid(), ccode)) {
			regresult = "code_error"; // 验证码错误
			return from + "regerror";
		}
		if (!pwd.equals(rcpwd)) {
			regresult = "pwd_error"; // 密碼不一致
			return from + "regerror";
		}
		if (memberService.isLoginExist(loginID)) {
			regresult = "id_exist"; // 帐号重复
			return from + "regerror";
		} else if (StringUtils.isNotBlank(mobile) && memberService.isMobileExist(mobile, member)) {
			regresult = "mobile_exist"; // 手机重复
			return from + "regerror";
		} else if (memberService.isEmailExist(mail)) {
			regresult = "mail_exist"; // mail重复
			return from + "regerror";
		} else {
			member.setPwd(pwd);
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			String aps = userData.getApplySource();
			if (StringUtils.isBlank(aps)) {
				member.setApplySource("yaodian100");
				member.setChannelId(Long.parseLong("0"));
				member.setChannelChild(null);
			} else {
				member.setApplySource(aps);
				String ch_id = userData.readValue("ch_id");
				if (StringUtils.isNotBlank(ch_id)) {
					member.setChannelId(Long.parseLong(ch_id));
				} else {
					member.setChannelId(channelService.getActivateChannelIdByName(aps));
				}
				member.setChannelChild(userData.getChChildCookie());
			}
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);

			logger.debug("register cookie == " + new Date().toString() + "  host():" + host + ", apply source{}:" + aps
					+ ", loginId{}:" + loginID);

			if (!from.equals("act")) {
				if (StringUtils.isNotBlank(mobile)) {
					member = memberService.saveMobileMember(member);

					try {
						String pr = userData.readRawValue("pr");
						String mgmCouponid = userData.readRawValue("mgmCouponid");
						if ("mgm".equals(pr)) {
							mgmService.updateMgmCoupon(mgmCouponid, member.getMemberId());

							mgmName = mgmService.getMgmCouponInfo(mgmCouponid).getUserName();// 获取发送者的name
							cpItem = mgmService.getCoupon(mgmCouponid);
							userData.writeRawValue("mgmCouponid", null);
							userData.writeRawValue("pr", null);
						}

					} catch (Exception e) {
						e.printStackTrace();
					}
					return "waitmobileactive";
				} else {
					member = memberService.saveMember(member);
					return "waitactivate";
				}
			} else {
				if (StringUtils.isNotBlank(mobile)) {
					member = memberService.saveMobileMember(member);
					regresult = "success";
				} else {
					member = memberService.saveMember(member);
					regresult = "success";
				}
			}
		}

		return from + "regerror";
	}

	public String checkRegData() throws CoreException, Exception {
		actionResult = "";
		switch (Integer.parseInt(c_id)) {
		case 1:
			if (memberService.isLoginExist(loginID)) {
				actionResult = "exist"; // 帐号重复
			}
			return "checkRegData";
		case 2:
			if (memberService.isEmailExist(mail)) {
				actionResult = "exist"; // mail重复
			}
			return "checkRegData";
		case 3:
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			if (!checkCode(userData.getImageValid(), ccode)) {
				actionResult = "error"; // 验证码错误
			}
			return "checkRegData";
		case 4:
			if (memberService.isMobileExist(mobile, (isLogin() ? member : null))) {
				actionResult = "exist"; // 手機重复
			}
			return "checkRegData";
		}
		return "";
	}

	public String waitactivate() {
		member = memberService.getMemberByLoginId(loginID);
		return "waitactivate";
	}

	public String actRegSuccess() {
		member = memberService.getMemberByLoginId(loginID);
		mobile = member.getMobile();
		mail = member.getEmail();
		if (StringUtils.isNotBlank(mobile)) {
			return "waitmobileactive";
		} else {
			return "waitactivate";
		}

	}

	private boolean isLogin() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		if (StringUtils.isNotBlank(userData.getNickname())) {
			loginID = userData.getNickname();
			nickId = loginID;
		}
		String tmp = userData.getLoginId();
		if (StringUtils.isNotBlank(tmp)) {
			member = memberService.getMemberByLoginId(tmp, request.getServerName());
		} else {
			return false;
		}
		if (member == null) {
			return false;
		}
		if (!request.getServerName().equals(userData.getLoginDamain())) {
			// 登入domain不同, 强制登出
			userData.clearAll();
			return false;
		}
		return true;
	}

	private boolean isNumeric(String str) {
		for (int i = 0; i < str.length(); i++) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Logout
	 * 
	 * @return
	 * @throws Exception
	 */
	public String jsonlogout() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		userData.clearAll();
		return "jsonlogout";
	}

	/**
	 * user login
	 * 
	 * @return
	 * @throws Exception
	 */
	public String login() throws Exception {
		loginresult = "";
		System.out.println("=======mgm进行  登录验证=====");
		if (StringUtils.isBlank(loginID) || StringUtils.isBlank(pwd)) {
			return "loginError";
		}
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		// get ip
		String host = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(host)) {
			host = request.getRemoteAddr();
		}
		String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

		if (null != remember) {
			nickId = loginID;
		}
		if (null != redirect_url) {
			pathparam = redirect_url;
		}
		if (isNumeric(loginID)) {
			member = memberService.getMemberByMobile(loginID);
		} else if (loginID.contains("@")) {
			member = memberService.getMemberByEmail(loginID);
		} else {
			member = memberService.getMemberByLoginId(loginID);
		}
		if (null == member) {
			loginresult = "unfind"; // 帐号不存在
			String pr = userData.readRawValue("pr");
			if ("mgm".equals(pr)) {
				System.out.println("=======mgm账号不存在=====");
				return "mgmlogin";
			}

			return "loginError";
		} // else if (member.getStatus().equals("10")) {
		// loginresult = "lock"; // 帐号已锁定
		// return "loginError";
		// }
		if ("nonmember".equals(member.getApplySource()) && null == member.getActivateExpireDate()) {
			loginresult = "nonmember"; // 非会员
			String pr = userData.readRawValue("pr");
			if ("mgm".equals(pr)) {
				return "mgmlogin";
			}
			return "loginError";
		}

		if (errTimes > 3 && !checkCode(userData.getImageValid(), ccode)) {
			loginresult = "code_error"; // 验证码错误
			memberService.saveFrontendLoginHistory(member, clientIp, "1");
			errTimes = memberService.getLoginHistorySize(member.getLoginId(), null, null);
			// if (memberService.getLoginHistorySize(member.getLoginId(), null,
			// null) > LOGINERROR_TIMES) {
			// memberService.saveFrontendLoginBlackList(member.getLoginId());
			// }
			String pr = userData.readRawValue("pr");
			if ("mgm".equals(pr)) {
				return "mgmlogin";
			}
			return "loginError";
		}

		if (null == memberService.loginPwdCheck(pwd, member)) {
			loginresult = "pwd_error"; // 密码错误
			memberService.saveFrontendLoginHistory(member, clientIp, "2");
			errTimes = memberService.getLoginHistorySize(member.getLoginId(), null, null);
			if (errTimes > LOGINERROR_TIMES) {
				String pr = userData.readRawValue("pr");
				if ("mgm".equals(pr)) {
					return "mgmlogin";
				}
				return "forgetpwd";
				// memberService.saveFrontendLoginBlackList(member.getLoginId());
			}
			String pr = userData.readRawValue("pr");
			if ("mgm".equals(pr)) {
				return "mgmlogin";
			}
			return "loginError";
		}
		if (member.getActiveDate() == null) { // 帐号未激活
			if (StringUtils.isNotBlank(member.getActivateToken())) {
				loginID = member.getLoginId();
				mail = member.getEmail();
				return "waitactivate";
			} else {
				actionResult = "fromlogin";
				loginID = member.getLoginId();
				mobile = member.getMobile();
				return "waitmobileactive";
			}
		}

		LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
		if (null != loginHistory) {
			member.setLastLoginTime(loginHistory.getLoginTime());
			memberService.update(member);
			memberService.deleteLoginHistory(member.getLoginId());
		}
		memberService.saveFrontendLoginHistory(member, clientIp);
		memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());
		userData.setLoginId(member.getLoginId());
		userData.setMemberId(member.getMemberId());
		if (null == remember) {
			userData.clearNickname();
		} else {
			userData.setNickname(loginID);
		}
		// 检查购物车，若为空，直接产生一个
		CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
		if (cartOrders == null) {
			cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
		}
		String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

		cartOrders = processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);

		// 记录购物车商品数量
		cartOrders = cartOrdersService.get(cartOrders.getCartId());
		userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		return "loginOK";
	}

	private CartOrders processMoveTmpCartToCartOrder(String tmpCartid, String memberCartId,
			CartOrdersService cartordersService, UserData userData) throws Exception {
		// 若memberCartId為空，則新增一個cartOrders
		// logger.info("memberCartId:{}", memberCartId);
		CartOrders cartOrders = null;

		if (memberCartId == null) {
			cartOrders = cartordersService.createCart(userData.getMemberId(), null, null, null, 0, null, null);
			memberCartId = cartOrders.getCartId();
			userData.writeRawValue("cartid", cartOrders.getCartId());
			// memberCartId = createNewCartOrders(memberCartId, userData);
		} else {
			cartOrders = cartordersService.getCart(memberCartId, null);
		}
		// logger.info("cartOrders:{}", cartOrders);
		if (StringUtils.isNotBlank(tmpCartid)) {
			CartOrders tmpCart = cartordersService.get(tmpCartid);
			if (null != tmpCart) {
				boolean hasTempQP = false;
				// 检查暂存购物车内是否有满额购，若有，移除会员购物车内之满额购
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {
					if (cop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
						// 若有满额购
						hasTempQP = true;
					}
				}
				if (hasTempQP) {
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (memberCop.getProdTp().equals(Product.PRODUCT_TYPE.QUOTAFILLED.getValue())) {
							cartOrders.getCartOrderProducts().remove(memberCop);
							break;
						}
					}
				}

				// 將暫存的車移至cartOrderProduct
				for (CartOrderProduct cop : tmpCart.getCartOrderProducts()) {

					boolean isItemExists = false;
					for (CartOrderProduct memberCop : cartOrders.getCartOrderProducts()) {
						if (cop.getProdId().equals(memberCop.getProdId()) && cop.getProdSpecId().equals(memberCop.getProdSpecId())) {
							isItemExists = true;
							break;
						}
					}
					if (!isItemExists) {
						CartOrderProduct tmpcop = new CartOrderProduct();
						// tmpcop.setAmount(new BigDecimal(0.00));
						BeanUtils.copyProperties(cop, tmpcop, new String[] { "cartOrderProdId", "cartOrder", "coupon",
								"modifyDate", "details" });
						// logger.info("tmpcop:{}", tmpcop.getAmount());
						cartOrders.addCartOrderProduct(tmpcop);
						for (CartOrderProductDetail detail : cop.getDetails()) {
							CartOrderProductDetail cloneDetail = new CartOrderProductDetail();
							BeanUtils.copyProperties(detail, cloneDetail, new String[] { "cartOrderDetailId", "cartOrderProdId",
									"orderProduct", "cartId", "cartOrder", "modifyDate", "details" });
							tmpcop.addDetail(cloneDetail);

						}
					}
				}
				// 刪除暫存車的cartOrders
				cartOrders = cartordersService.save(cartOrders);
				cartordersService.delete(tmpCart);
			}
		}
		return cartOrders;
	}

	public String alipayLogin() throws Exception {
		pathparam = new String(Base64.decode(pathparam.getBytes()));
		member = memberService.getMemberByLoginId(loginID);
		if (null == member) {
			member = new Member();
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			member.setLoginId(loginID);
			if (!mail.contains("@")) {
				member.setEmail("xx");
			} else {
				member.setEmail(mail);
			}
			member.setName(StringUtils.substring(contactName, 0, 16));
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());
			member.setPwd("xx");

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource("alipaymember");
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
		}
		autoLogin(memberService.getMemberByLoginId(member.getLoginId()),
				StringUtils.defaultString(member.getName(), member.getLoginId()));
		return "loginOK";
	}

	/**
	 * 360一站通 信任登入
	 * 
	 * @return
	 * @throws Exception
	 */
	public String hao360Login() throws Exception {
		pathparam = new String(Base64.decode(pathparam.getBytes()));
		String name = new String(contactName.getBytes("ISO-8859-1"), "utf-8");

		member = memberService.getMemberByLoginId(loginID);
		if (null == member) {
			member = new Member();
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			member.setLoginId(loginID);
			member.setEmail("xx");
			member.setName(StringUtils.substring(name, 0, 16));
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());
			member.setPwd("xx");

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource("hao360member");
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
		}
		autoLogin(memberService.getMemberByLoginId(member.getLoginId()), null);
		return "loginOK";
	}

	/**
	 * 返利信任登入
	 * 
	 * @return
	 * @throws CoreException
	 * @throws Exception
	 */
	public String fanli() throws CoreException, Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		TreeMap<String, String> map;
		try {
			map = parseFanli(request.getQueryString());
			// set ad.do cookie
			Long channelId = channelService.getActivateChannelIdByName("fanli");
			if (channelId.compareTo(Long.parseLong("0")) != 0) {
				HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
						ServletActionContext.HTTP_RESPONSE);
				UserData userData = new UserData(request, response);
				userData.setTimeOut(60 * 60 * 24 * 30);
				userData.setApplySource("fanli");
				userData.writeValue("ch_id", channelId.toString());
				if (StringUtils.isNotBlank(remember)) {
					userData.writeValue("ch_child", "u_id=" + remember + "&username="
							+ (StringUtils.isNotBlank(loginID) ? loginID : ""));
				}
				if (pathparam.contains("?")) {
					pathparam += "&site=" + "fanli";
				} else {
					pathparam += "?site=" + "fanli";
				}
				pathparam += "&hpp=" + channelId;
			}
			if (null == map) {
				return "logout";
			}
		} catch (Exception e) {
			System.out.println("fanli error{}:" + e.getMessage());
			return "logout";
		}

		member = memberService.getMemberByLoginId(loginID);
		if (null == member) {
			member = new Member();
			member.setLoginId(loginID);
			member.setEmail(StringUtils.isNotBlank(mail) ? mail : "xx");
			member.setChannelChild(map.get("usersafekey")); // 用户安全码
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());
			member.setPwd("xx");
			if ("true".equals(map.get("syncaddress"))) {
				member.setName(StringUtils.substring(map.get("name"), 0, 100));
				member.setProvince(map.get("province"));
				member.setCity(map.get("city"));
				member.setDistrict(map.get("area"));
				member.setAddr(map.get("address"));
				member.setZipCode(map.get("zip"));
				member.setHomePhone(map.get("phone"));
				member.setTempMobile(map.get("mobile"));
			}

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource("fanlimember");
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
		} else if (!member.getChannelChild().equalsIgnoreCase(map.get("usersafekey"))) {
			return "logout";
		}
		autoLogin(memberService.getMemberByLoginId(member.getLoginId()), null);
		return "loginOK";
	}

	public String qqfanli() throws CoreException, Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		try {
			boolean isCorrect = parseQQFanli(request.getQueryString());
			if (!isCorrect) {
				pathparam = "";
				return "logout";
			}
		} catch (Exception e) {
			System.out.println("qqfanli error{}:" + e.getMessage());
			pathparam = "";
			return "logout";
		}
		member = memberService.getMemberByLoginId(loginID);
		if (null == member) {
			member = new Member();
			member.setLoginId(loginID);
			member.setName(StringUtils.substring(qqName, 0, 100));
			member.setEmail("xx");
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());
			member.setPwd("xx");

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource("qqfanlimember");
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
		}
		autoLogin(memberService.getMemberByLoginId(member.getLoginId()), qqName);
		return "loginOK";
	}

	/**
	 * Logout - clear cookies
	 * 
	 * @return
	 * @throws Exception
	 */
	public String logout() throws Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		userData.clearAll();
		if (!(StringUtils.contains(pathparam, "/category/") || StringUtils.contains(pathparam, "/product/")
				|| StringUtils.contains(pathparam, "/help/") || StringUtils.contains(pathparam, "/act/") || StringUtils
					.contains(pathparam, "/info/"))) {
			pathparam = "http://" + request.getServerName();
		}
		return "logout";
	}

	/**
	 * 帳號啟動 - 手机
	 * 
	 * @return
	 * @throws Exception
	 * @throws CoreException
	 */
	public String mobileRegActivate() throws Exception {
		if (null != (member = memberService.setMobileMemberActive(loginID, ccode))) {
			checkGift(member);
			autoLogin(member, null);
			// 为mgm用户充值礼券
			MgmCoupon mgmCoupon = mgmService.checkMgmMember(member.getMemberId());
			if (mgmCoupon != null) {// 判断是不是mgm用户
				try {
					mgmName = mgmService.getMgmCouponInfo(mgmCoupon.getCouponId()).getUserName();// 获取发送者的name
					CouponItem couponItem = couponService.getCouponItemByCode(mgmCoupon.getCouponId());
					couponService.regCouponItem(couponItem, mgmCoupon.getToMemeberId());
					mgmService.updateIsuseCoupon(mgmCoupon.getCouponId());

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			return "mobile_activate_success";
		}
		member = memberService.getMemberByLoginId(loginID);
		mobile = member.getMobile();
		actionResult = "ccode_error";
		return "waitmobileactive";
	}

	/**
	 * 重新发送注册激活简讯
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String mobileresend() throws CoreException {
		member = memberService.getMemberByLoginId(loginID);
		actionResult = memberService.resendRegActivateSMS(member, mobile);
		mobile = member.getMobile();
		return "waitmobileactive";
	}

	/**
	 * 人工验证手机
	 * 
	 * @return
	 */
	public String jsonCrmCheckMobile() {
		actionResult = "";
		member = memberService.get(UserLoginData.getMemberId());
		if (StringUtils.isBlank(member.getTempMobile())) {
			actionResult = "empty";
			return "jsonCrmCheckMobile";
		}
		if (StringUtils.isBlank(mobile)) {// from 結帳頁
			mobile = member.getTempMobile();
			actionResult = mobile + ",";
		}
		// from 0:注册 1:修改 2:订单
		actionResult += csService.createCrmCheckMobile(mobile, memberId, from);
		return "jsonCrmCheckMobile";
	}

	/**
	 * 激活信箱 - 導至再確認頁面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String modifyActive() throws Exception {
		try {
			String[] data = PasswordUtils.decodePassword(code, null).split("-");
			if (data.length == 2) {
				member = memberService.get(UserLoginData.getMemberId());
				if (!UserLoginData.getMemberId().equals(data[0])) {
					return "not_match"; // 登入帳戶與激活連結的memberId不一致
				}
				if (null == memberService.checkActivateData(data[0], data[1])) {
					return "activateError"; // 激活連結 token 無效
				}
				if (StringUtils.isBlank(member.getEmail()) || "xx".equals(member.getEmail())) {
					return activateModifyEmail();
				}
				return "recheckEmail";
			}
		} catch (Exception e) {
			// decode 失敗
			return "activateError";
		}
		return "activateError";
	}

	/**
	 * 切换到修改个人资料页
	 * 
	 * @return
	 */
	public String modifydata() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		member = memberService.checkMobileModifyCount(member);
		if (null == member.getLastMobileModifyDate()) {
			canModifyDate = DateUtils.addDays(new Date(0), -10);
		} else {
			canModifyDate = DateUtils.addDays(member.getLastMobileModifyDate(), 5);
		}
		return "modifydata";
	}

	/**
	 * 更新性别生日
	 * 
	 * @return
	 * @throws ParseException
	 */
	public String updateSexAndBirthday() throws ParseException {
		member = memberService.get(UserLoginData.getMemberId());
		member = memberService.updateSexAndBirthday(member, sex, birthday);
		return "modifydata";
	}

	/**
	 * 執行订阅/退订邮件
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String modifyedm() throws CoreException {
		if (edm == null) {
			edm = "N";
		} else {
			edm = "Y";
		}
		if (sms == null) {
			sms = "N";
		} else {
			sms = "Y";
		}
		member = memberService.updateEDMStatus(UserLoginData.getLoginId(), edm, sms);
		if (member != null) {
			actionResult = "success";
		}
		return "modifyedm";
	}

	/**
	 * 切换到修改e-mail页
	 * 
	 * @return
	 */
	public String modifyemail() {
		member = memberService.get(UserLoginData.getMemberId());
		mail = "";
		return "modifyemail";
	}

	/**
	 * 切换到修改手机页
	 * 
	 * @return
	 */
	public String modifymobile() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		if (StringUtils.isBlank(member.getMobile()) && StringUtils.isNotBlank(member.getTempMobile())) {
			actionResult = "login_ok";
			return "modifymobilecheck";
		}
		return "modifymobile";
	}

	/**
	 * 验证效验码&更新手机
	 * 
	 * @return
	 */
	public String modifyMobileActivate() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		String type;
		if (StringUtils.isBlank(member.getMobile())) {
			type = "new_";
		} else {
			type = "modify_";
		}
		if (!ccode.equalsIgnoreCase(member.getActivateMobileToken())) {
			actionResult = "ccode_error";
			return "modifymobilecheck";
		}
		if (null == memberService.setModifyMobileActive(member)) {
			actionResult = type + "mobile_exist";
		} else {
			actionResult = type + "success";
		}
		return "modifymobileok";
	}

	/**
	 * 检查手机激活验证码
	 * 
	 * @return
	 */
	public String jsonCheckActivateMobileCode() {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		member = memberService.get(memberId);
		actionResult = "";

		if (!ccode.equalsIgnoreCase(member.getActivateMobileToken())) {
			actionResult = "ccode_error";
		}
		return "checked";
	}

	/**
	 * 验证校验码
	 * 
	 * @return
	 */
	public String modifymobilecheck() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		actionResult = StringUtils.isBlank(member.getMobile()) ? "new_mobile" : "modify_mobile";
		if (StringUtils.isBlank(ccode)) {
			ccode = "error";
			return "not_match";
		}
		if (!PasswordUtils.decodePassword(ccode, null).equals(member.getLoginId())) {
			return "not_match"; // 登入帳戶與激活連結的loginId不一致
		}
		if (StringUtils.isBlank(member.getActivateMobileToken())) {
			ccode = "error";
			return "not_match";
		}
		actionResult = "login_ok";
		return "modifymobilecheck";
	}

	/**
	 * 修改密码
	 * 
	 * @return
	 * @throws Exception
	 */
	public String modifypwd() throws Exception {
		member = memberService.getMemberByLoginId(loginID);
		if (null == memberService.loginPwdCheck(opwd, member)) {
			modifyPwdResult = "opwd_error";
			return "tomodifypwd";
		}
		memberService.updateMemberPwd(loginID, pwd);
		memberService.sendModifyPwdOkMail(loginID);
		// success
		return "modifypwdok";
	}

	public String myyaodian() throws Exception {
		member = memberService.get(UserLoginData.getMemberId());
		CommonCriteria crit = new CommonCriteria();
		crit.addEq("memberId", member.getMemberId());
		crit.addEq("categoryId", null);
		crit.addNe("shelfPrice", null);
		crit.addNe("is_delete", "Y");
		viewWishList = memberService.getViewWishLists(0, 8, crit, null);
		annList = announcementService.getVisibleAnnouncementList(6);
		this.memberMessageList = announcementService.getMemberMessageList();
		showMsg = memberService.showCompleteInfoDialog(member);

		numOrderCommet = orderCommentService.getOrderCommentListByMemberId(UserLoginData.getMemberId(), "", "").toString();
		return "myyaodian";
	}

	/**
	 * 切换到新增手机页
	 * 
	 * @return
	 */
	public String newmobile() {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		return "newmobile";
	}

	@SuppressWarnings("unchecked")
	public String redirect() throws MalformedURLException {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		Menu channelNameMenu = menuService.get("Channel.Name");
		if (null == channelNameMenu.getOptions().get(site)) {
			site = "yaodian100";
		}

		String queryString = request.getQueryString();
		userData.setTimeOut(60 * 60 * 24 * 30);
		userData.setApplySource(site);
		userData.writeValue("ch_child", getChannelChild(queryString));

		if (site.startsWith("baidu")) {
			site = StringUtils.splitByWholeSeparator(site, "?bdclkid=")[0];
		}
		if (StringUtils.isBlank(url) || !url.startsWith(ServerValue.getFrontHostname())) {
			url = ServerValue.getFrontHostname();
		}
		if (url.contains("?")) {
			url += "&site=" + site;
		} else {
			url += "?site=" + site;
		}
		if (!"espnstar".equalsIgnoreCase(site)) {
			Enumeration enums = request.getParameterNames();
			while (enums.hasMoreElements()) {
				String pname = enums.nextElement().toString();
				if (!(pname.equals("url") || pname.equals("site"))) {
					url += "&" + pname + "=" + request.getParameter(pname);
				}
			}
		}
		pathparam = url;
		String host = request.getHeader("X-Forwarded-For");
		if (StringUtils.isBlank(host)) {
			host = request.getRemoteAddr();
		}
		logger.debug("redirect cookie == " + new Date().toString() + "  host():" + host + ", apply source{}:" + site
				+ ", referer{}:" + request.getHeader("referer"));
		if ("adwayspc".equals(site)) {
			return "getapplysourceok_jsp";
		}
		return "getapplysourceok";
	}

	/**
	 * 帳號啟動
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String regActive() throws CoreException {
		try {
			String[] data = PasswordUtils.decodePassword(code, null).split("-");
			if (data.length == 2) {
				member = memberService.setMemberActive(data[0], data[1]);
				if (null != member) {
					checkGift(member);
					autoLogin(member, null);
					return "regsuccess";
				}
			}
		} catch (Exception e) {
			logger.debug("MemberAction", "regActive", e);
			return "activatefail";
		}
		return "activatefail";
	}

	/**
	 * 切换到注册成功页
	 * 
	 * @return
	 */
	public String regsuccess() {
		return "regsuccess";
	}

	/**
	 * 重新发送注册激活信
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String resend() throws CoreException {
		member = memberService.getMemberByLoginId(loginID);
		if (null != member.getActiveDate()) {
			actionResult = "activated";
			return "waitactivate";
		}
		actionResult = memberService.resendRegActivateMail(member, mail, pwd);
		mail = member.getEmail();
		return "waitactivate";
	}

	/**
	 * 重发找回密码简讯
	 * 
	 * @return
	 */
	public String resendforgetmobilepwd() {
		member = memberService.getMemberByLoginId(loginID);
		memberService.getFtMemberPwdmobile(member, mobile);
		actionResult = "resend_ok";
		return "forgetpwdmobilecheck";
	}

	/**
	 * 重送修改email激活信
	 * 
	 * @return
	 * @throws Exception
	 */
	public String resendModifyEmail() throws Exception {
		actionResult = memberService.sendModifyActivateMail(loginID, mail, pwd);
		member = memberService.getMemberByLoginId(loginID);
		mail = member.getTempEmail();
		actionResult = "m_" + actionResult;
		return "modifyemailok";
	}

	/**
	 * 新增
	 * 
	 * @return
	 * @throws Exception
	 */
	public String saveAddressBook() throws Exception {
		AddressBook adBook;
		if (Integer.parseInt(abId) != -1) {
			adBook = memberService.getAddressBook(Long.parseLong(abId));
		} else {
			String memberId = UserLoginData.getMemberId();
			CommonCriteria crit = new CommonCriteria();
			crit.addEq("memberId", memberId);
			abList = memberService.getAddressBookList(crit);
			if (abList.size() >= 20) {
				actionResult = "error-超过20笔资料";
				return "jsonSaveAddressBook";
			}
			adBook = new AddressBook();
			adBook.setMemberId(memberId);
		}
		adBook.setContactName(contactName);
		adBook.setProvince(province);
		adBook.setCity(city);
		adBook.setDistrict(district);
		adBook.setZipCode(zipCode);
		adBook.setAddr(addr);
		adBook.setMobile(StringUtils.isBlank(mobile) ? null : mobile);
		if (StringUtils.isBlank(phone)) {
			adBook.setAreaCode(null);
			adBook.setPhone(null);
			adBook.setExtension(null);
		} else {
			adBook.setAreaCode(areaCode);
			adBook.setPhone(phone);
			adBook.setExtension(StringUtils.isBlank(extension) ? null : extension);
		}
		if (memberService.checkAddressBookExist(adBook)) {
			actionResult = "error-资料已存在";
		} else {
			if (Integer.parseInt(abId) != -1) {
				adBook = memberService.updateAddressBook(adBook);
			} else {
				adBook = memberService.saveAddressBook(adBook);
			}
			actionResult = "success-" + adBook.getId();
		}
		return "jsonSaveAddressBook";
	}

	/**
	 * 发送重设密码email or sms
	 * 
	 * @return
	 * @throws Exception
	 */
	public String sendforgetpwd() throws Exception {
		actionResult = "";
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		if (!checkCode(userData.getImageValid(), ccode)) {
			actionResult = "code_error"; // 验证码错误
			return StringUtils.isNotBlank(mail) ? "goforgrtpwdemail" : "goforgrtpwdmobile";
		}
		if (StringUtils.isBlank(loginID)) {// 非會員
			member = memberService.getMemberByEmail(mail);
			if (null == member) {
				actionResult = "mail_not_exist"; // 郵箱未登錄
				return "goforgrtpwdemail";
			}
			if (!"nonmember".equals(member.getApplySource())) {
				return "forgetpwd";
			}
			loginID = member.getLoginId();
		} else {
			member = memberService.getMemberByLoginId(loginID);
		}
		if (StringUtils.isNotBlank(mail)) { // 邮箱找回
			/*
			 * if (StringUtils.isBlank(member.getEmail())) { // 手机会员未验证邮箱 if (!mail.equals(member.getTempEmail())) {
			 * actionResult = "mail_not_match"; return "goforgrtpwdemail"; } } else
			 */
			if (!mail.equals(member.getEmail())) {
				actionResult = "mail_not_match"; // 帐户名与注册邮箱不匹配
				return "goforgrtpwdemail";
			}
			memberService.getFtMemberPwd(loginID, mail);
			return "forgetpwdok";
		} else { // 手机找回
			if (!mobile.equals(member.getMobile())) {
				actionResult = "mobile_not_match"; // 帐户名与注册手机不匹配
				return "goforgrtpwdmobile";
			}
			memberService.getFtMemberPwdmobile(member, mobile);
			return "forgetpwdmobilecheck";
		}
	}

	private void autoLogin(Member member, String showName) throws Exception {
		if (null != member) {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			// get ip
			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			String clientIp = StringUtils.isBlank(host) ? "" : (host.length() > 100 ? host.substring(0, 100) : host);

			UserData userData = new UserData(request, response);
			userData.clearAll();
			userData.setLoginId(member.getLoginId());
			userData.setMemberId(member.getMemberId());
			if (StringUtils.isNotBlank(showName)) {
				userData.setShowName(showName);
			}

			memberService.checkBalance(member);
			LoginHistory loginHistory = memberService.getLastLoginHistory(member.getLoginId());
			if (null != loginHistory) {
				member.setLastLoginTime(loginHistory.getLoginTime());
				memberService.update(member);
				memberService.deleteLoginHistory(member.getLoginId());
			}

			memberService.saveFrontendLoginHistory(member, clientIp);
			memberService.checkLoginBonus(member, request.getServerName(), userData.getApplySource());

			CartOrders cartOrders = cartOrdersService.getCart(member.getMemberId(), null);
			if (cartOrders == null) {
				cartOrders = cartOrdersService.createCart(member.getMemberId(), null, null, null, 0, null, null);
			}
			String tmpCartid = StringUtils.defaultString(userData.readRawValue("cartid"));

			cartOrders = processMoveTmpCartToCartOrder(tmpCartid, cartOrders.getCartId(), cartOrdersService, userData);
			// logger.debug("autoLogin == " + new Date().toString() +
			// "  host():" + host + ", apply source{}:"
			// + member.getApplySource() + ", loginId{}:" +
			// member.getLoginId());
			// 记录购物车商品数量
			cartOrders = cartOrdersService.get(cartOrders.getCartId());
			userData.writeRawValue(UserData.NAME_YAODIAN100_CART_ITEMS, String.valueOf(cartOrders.getProductSum()));
		}
	}

	/**
	 * 结帐流程中验证手机
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String regMobile() {
		if (StringUtils.isBlank(mobile)) {
			actionResult = "请输入手机号码";
			return "regMobile";
		}
		if (mobile.length() != 11) {
			actionResult = "手机号码格式错误";
			return "regMobile";
		}
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		actionResult = memberService.sendModifyMobileActivateSms(member, mobile, null, false);
		if ("error".equals(actionResult)) {
			actionResult = "您已超过使用短信服务的上限";
		} else if ("mobile_exist".equals(actionResult)) {
			actionResult = "此手机号码已注册，请改用其他手机号码";
		} else {
			actionResult = "";
		}
		return "regMobile";
	}

	/**
	 * 结帐流程中激活手机
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String activeMobile() {
		if (StringUtils.isBlank(ccode)) {
			actionResult = "请输入验证码";
			return "activeMobile";
		}
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		if (!ccode.equalsIgnoreCase(member.getActivateMobileToken())) {
			actionResult = "验证碼错误";
			return "activeMobile";
		}
		if (null == memberService.setModifyMobileActive(member)) {
			actionResult = "该手机已被使用";
		} else {
			actionResult = "";
		}
		return "activeMobile";
	}

	public String topbar() {
		return "topbar";
	}

	public void setA_id(String aId) {
		a_id = aId;
	}

	public void setAbId(String abId) {
		this.abId = abId;
	}

	public void setAbList(List<AddressBook> abList) {
		this.abList = abList;
	}

	public void setActionResult(String actionResult) {
		this.actionResult = actionResult;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	public void setAnnList(List<Announcement> annList) {
		this.annList = annList;
	}

	public void setAnnouncementService(AnnouncementService announcementService) {
		this.announcementService = announcementService;
	}

	public void setAreaCode(String areaCode) {
		this.areaCode = areaCode;
	}

	public void setC_id(String cId) {
		c_id = cId;
	}

	/**
	 * @param canModifyDate the canModifyDate to set
	 */
	public void setCanModifyDate(Date canModifyDate) {
		this.canModifyDate = canModifyDate;
	}

	public void setCcode(String ccode) {
		this.ccode = ccode;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public void setContactName(String contactName) {
		this.contactName = contactName;
	}

	public void setDistrict(String district) {
		this.district = district;
	}

	/**
	 * @param edm the edm to set
	 */
	public void setEdm(String edm) {
		this.edm = edm;
	}

	public void setExtension(String extension) {
		this.extension = extension;
	}

	public void setL_id(String lId) {
		l_id = lId;
	}

	public void setL_type1(String lType1) {
		l_type1 = lType1;
	}

	public void setLoginID(String loginID) {
		this.loginID = loginID;
	}

	public void setLoginresult(String loginresult) {
		this.loginresult = loginresult;
	}

	public void setM_id(String mId) {
		m_id = mId;
	}

	public void setMail(String mail) {
		this.mail = mail;
	}

	public void setMember(Member member) {
		this.member = member;
	}

	public void setMemberGift(MemberGift memberGift) {
		this.memberGift = memberGift;
	}

	public void setMemberService(MemberService memberService) {
		this.memberService = memberService;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	public void setModifyPwdResult(String modifyPwdResult) {
		this.modifyPwdResult = modifyPwdResult;
	}

	public void setNickId(String nickId) {
		this.nickId = nickId;
	}

	public void setOpwd(String opwd) {
		this.opwd = opwd;
	}

	public void setPathparam(String pathparam) {
		this.pathparam = pathparam;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public void setProduct(Product product) {
		this.product = product;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}

	public void setProvince(String province) {
		this.province = province;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public void setRcpwd(String rcpwd) {
		this.rcpwd = rcpwd;
	}

	public void setRd(String rd) {
		this.rd = rd;
	}

	public void setRedirect_url(String redirectUrl) {
		redirect_url = redirectUrl;
	}

	public void setRegresult(String regresult) {
		this.regresult = regresult;
	}

	public void setRemember(String remember) {
		this.remember = remember;
	}

	/**
	 * @param site the site to set
	 */
	public void setSite(String site) {
		this.site = site;
	}

	public void setSpec(Specification spec) {
		this.spec = spec;
	}

	/**
	 * @param url the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	public void setViewWishList(List<ViewWishList> viewWishList) {
		this.viewWishList = viewWishList;
	}

	public void setZipCode(String zipCode) {
		this.zipCode = zipCode;
	}

	/**
	 * switch to login page
	 * 
	 * @return
	 * @throws Exception
	 */
	public String tologin() throws Exception {
		logger.debug("==========进行登录===============");
		errTimes = 0;
		xerrTimes = 4;
		if (StringUtils.isNotBlank(redirect_url) && redirect_url.startsWith(ServerValue.getFrontHostname())) {
			pathparam = redirect_url;
		} else {
			pathparam = ServerValue.getFrontHostname();
		}
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		String domainSrc = request.getServerName();
		String pclady = menuService.get("SystemValue").getOptions().get("pclady").getMemo1();
		String pr = request.getParameter("pr");
		logger.debug("=======pr的值============" + pr);
		if (pr != null && "mgm".equals(pr)) {
			UserData userData = new UserData(request, response);
			userData.writeRawValue("pr", pr);
			logger.debug("==========mgm  登录活动页面==END==============");
			return "mgmlogin";
		}
		logger.debug("==========跳过了  mgm  进入正常的登录页面================");
		if (domainSrc.equals(pclady)) {
			String cobrandingLogin = "http://buy.pclady.com.cn/yaodianlogin.jsp?retUrl=";
			pathparam = cobrandingLogin + URLEncoder.encode(redirect_url, "utf-8");
			return "loginOK";
		} else if (domainSrc.endsWith("yaodian100.com")) {
			if (isLogin()) {
				return "loginOK";
			} else {
				if (StringUtils.isNotBlank(yid)) {
					loginID = yid;
				}
				return "tologin";
			}
		} else {
			String cobrandingLogin = "http://" + domainSrc + "/" + ServerValue.getFrontContextPath()
					+ "/cobranding/memberLogin.do?coBrand=" + domainSrc + "&sendTo=";
			// cobrandingLogin = URLEncoder.encode(cobrandingLogin, "utf-8");
			pathparam = cobrandingLogin + URLEncoder.encode(redirect_url, "utf-8");
			System.out.println(pathparam);
			return "loginOK";

		}
	}

	/**
	 * 改用email激活
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String tomailactivate() throws CoreException {
		member = memberService.getMemberByLoginId(loginID);
		actionResult = memberService.resendRegActivateMail(member, null, null);
		mail = member.getEmail();
		return "waitactivate";
	}

	private String getChannelChild(String qString) {
		StringBuffer sb = new StringBuffer();
		String[] ccArray = StringUtils.split(qString, "&");
		for (int i = 0; i < ccArray.length; i++) {
			if (!(StringUtils.startsWith(ccArray[i], "url=") || StringUtils.startsWith(ccArray[i], "site=") || StringUtils
					.startsWith(ccArray[i], "id="))) {
				sb.append(sb.length() == 0 ? "" : "&").append(ccArray[i]);
			}
		}
		return sb.toString();
	}

	/**
	 * 邮箱注册
	 * 
	 * @return
	 */
	public String tomailreg() {
		return "tomailreg";
	}

	/**
	 * 手机注册
	 * 
	 * @return
	 */
	public String tomobilereg() {
		return "tomobilereg";
	}

	/**
	 * 用户注册 MGM活动
	 * 
	 * @return
	 */
	public String tomgmreg() {

		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		System.out.println("=========mgm登录==============");
		pathparam = request.getParameter("redirect_url");
		String pr = request.getParameter("pr");
		String couponid = request.getParameter("couponid");
		UserData userData = new UserData(request, response);
		userData.writeRawValue("mgmCouponid", couponid);
		userData.writeRawValue("pr", pr);
		return "mgmreg";

	}

	/**
	 * 订阅/退订邮件頁
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String tomodifyedm() throws CoreException {
		member = memberService.getMemberByLoginId(UserLoginData.getLoginId());
		edm = member.getEdm();
		sms = member.getSms();
		return "modifyedm";
	}

	/**
	 * 切换到修改密码页
	 * 
	 * @return
	 */
	public String tomodifypwd() {
		modifyPwdResult = "";
		return "tomodifypwd";
	}

	/**
	 * 切换到收件人地址页
	 * 
	 * @return
	 * @throws CoreException
	 */
	public String tomyaddbook() throws Exception {
		abList = memberService.getAddressBookList(UserLoginData.getMemberId());
		return "myaddbook";
	}

	private boolean parseQQFanli(String s) throws UnsupportedEncodingException, InterruptedException, Exception {
		String su = URLDecoder.decode(s, "utf-8");

		String vkey = null;
		TreeMap<String, String> map = new TreeMap<String, String>();
		for (String skv : StringUtils.split(su, "&")) {
			String[] sa = StringUtils.split(skv, "=");
			if ("vkey".equals(sa[0])) {
				vkey = sa[1];
			} else {
				if (sa.length == 2) {
					map.put(sa[0], sa[1]);
				} else {
					map.put(sa[0], null);
				}
			}
			// md5(md5(参数列表+key1)+key2)
		}
		qqName = StringUtils.replace(URLDecoder.decode(map.get("viewinfo"), "utf-8"), "&nbsp;", " ");
		loginID = map.get("acct");
		String ts = map.get("ts");
		pathparam = map.get("url");

		if (StringUtils.isBlank(pathparam) || "/".equals(pathparam)) {
			pathparam = ServerValue.getFrontHostname();
		}
		DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		// 一天内有效
		if (df.parse(ts).getTime() < DateUtils.addDays(new Date(), -1).getTime()) {
			return false;
		}

		StringBuffer sb = new StringBuffer();
		for (String k : map.navigableKeySet()) {
			if (StringUtils.isNotEmpty(map.get(k))) {
				sb.append(map.get(k));
			}
		}
		sb.append(qqFanliKey1);
		String md1 = BytesUtil.md5Signature(sb.toString()).toLowerCase();
		String md2 = BytesUtil.md5Signature(md1 + qqFanliKey2).toLowerCase();
		return md2.equals(vkey);
	}

	private TreeMap<String, String> parseFanli(String s) throws UnsupportedEncodingException, InterruptedException,
			Exception {
		TreeMap<String, String> map = parseUrl(s, "gb2312");
		loginID = map.get("username");
		remember = map.get("u_id");
		mail = map.get("email");
		pathparam = map.get("url");
		if (StringUtils.isBlank(pathparam) || "/".equals(pathparam)) {
			pathparam = ServerValue.getFrontHostname();
		}
		// 超出五分钟 or 无资料
		if ("false".equals(map.get("syncname"))
				|| Long.parseLong(map.get("action_time") + "000") < DateUtils.addMinutes(new Date(), -5).getTime()) {
			logger.error("fanli error: 超出五分钟 or 无资料 " + map);
			return null;
		}
		String code = BytesUtil.md5Signature(map.get("username") + fanliKey + map.get("action_time"));
		// 验证码不合
		if (!code.equalsIgnoreCase(map.get("code"))) {
			logger.error("fanli error: 验证码不合 " + map);
			return null;
		}
		return map;
	}

	private TreeMap<String, String> parseUrl(String url, String type) throws UnsupportedEncodingException {
		TreeMap<String, String> map = new TreeMap<String, String>();
		for (String skv : StringUtils.split(url, "&")) {
			String[] sa = StringUtils.split(skv, "=");
			if (sa.length == 2) {
				map.put(sa[0], URLDecoder.decode(sa[1], type));
			} else {
				map.put(sa[0], null);
			}
		}
		return map;
	}

	/**
	 * switch to register page
	 * 
	 * @return
	 * @throws Exception
	 */
	public String toreg() {
		return "toreg";
	}

	public String xunleiLogin() throws CoreException, Exception {
		xerrTimes = 4;
		loginresult = "";
		if (StringUtils.isBlank(xloginID) || StringUtils.isBlank(pwd)) {
			loginresult = "xunleiError";
			return "loginError";
		}
		// 连续登入失败错误三次, 需输入验证码
		if (xerrTimes > 3) {
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
					ServletActionContext.HTTP_RESPONSE);
			UserData userData = new UserData(request, response);
			if (!checkCode(userData.getImageValid(), ccode)) {
				loginresult = "xunlei_code_error"; // 验证码错误
				return "loginError";
			}
		}
		try {
			String xAccount = xunLeiServiceImpl.getXunLeiAccountKey(xloginID, pwd);
			if (StringUtils.isBlank(xAccount)) {
				if (xerrTimes <= 3) {
					xerrTimes++;
				}
				loginresult = "xunleiError";
				return "loginError";
			}
			member = memberService.getMemberByLoginId(xAccount + "@xunlei");
			if (null == member) {
				member = new Member();
				HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
						ServletActionContext.HTTP_REQUEST);
				member.setLoginId(xAccount + "@xunlei");
				member.setPwd("xx");
				member.setEmail("xx");
				member.setRank("1");
				member.setStatus("00");
				member.setActiveDate(new Date());

				String host = request.getHeader("X-Forwarded-For");
				if (StringUtils.isBlank(host)) {
					host = request.getRemoteAddr();
				}
				member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
				member.setApplySource(XUNLEI_MEMBER);
				String domainSrc = request.getServerName();
				member.setDomainSrc(domainSrc);
				member = memberService.save(member);
				memberService.newBalance(member);
				MemberEvent me = memberService.checkMemberEvent(member);
				if (null != me) {
					pathparam = "http://" + request.getServerName() + ServerValue.getFrontContextPath() + "/member/"
							+ ("2".equals(me.getType()) ? "myBonus/tomybonus.do" : "myCoupon/tomycoupon.do");
				}
			}
			autoLogin(memberService.getMemberByLoginId(member.getLoginId()), null);
		} catch (Exception e) {
			logger.error("Xunlei login error: ", e);
			if (xerrTimes <= 3) {
				xerrTimes++;
			}
			loginresult = "xunleiError";
			return "loginError";
		}
		return "loginOK";
	}

	public void toqqlogin() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
		if (StringUtils.isBlank(redirect_url)) {
			redirect_url = ServerValue.getFrontHostname();
		}
		redirect_url = new String(Base64.encode(redirect_url.getBytes()));
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		String url = "http://openapi.qzone.qq.com/oauth/qzoneoauth_authorize?oauth_consumer_key="
				+ com.qq.config.Config.APP_ID;

		RequestToken token = new RequestToken();
		String request_token = null;
		request_token = token.getRequestToken();
		HashMap<String, String> tokens = ParseString.parseTokenString(request_token);
		String oauth_token = tokens.get("oauth_token");
		String oauth_token_secret = tokens.get("oauth_token_secret");
		UserData userData = new UserData(request, response);
		userData.writeRawValue("oauth_token_secret", oauth_token_secret);
		// request.getSession().setAttribute("oauth_token_secret",
		// oauth_token_secret);
		url += "&oauth_token=" + oauth_token;
		url += "&oauth_callback="
				+ URLEncoder.encode(com.qq.config.Config.OAUTH_CALLBACK + "?redirect_url=" + redirect_url, "UTF-8");
		response.sendRedirect(url);
	}

	public String qqlogin() throws CoreException, Exception {
		pathparam = new String(Base64.decode(redirect_url.getBytes()));
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		String oauth_token = request.getParameter("oauth_token");
		String openid = request.getParameter("openid");
		String oauth_signature = request.getParameter("oauth_signature");
		String oauth_vericode = request.getParameter("oauth_vericode");
		String timestamp = request.getParameter("timestamp");

		String qqshowvip = "";
		String qqtimestamp = "";
		String qqshowsignature = "";

		// QQ红钻参数
		qqshowsignature = request.getParameter("qqshowsignature");
		if (qqshowsignature != null && !qqshowsignature.equals("")) {

			// qqshowsignature参数解密
			Date currentdate = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
			String time = formatter.format(currentdate);
			// Option option = JspUtil.menuOption("SystemValue",
			// "qqshowruby");
			// String key = option.getMemo1() + time;
			String key = "showdian" + time;
			// String key = "showdian20110906";
			// 解析qqshowsignature
			String unbindQQshow = new String(CryptoUtil.aesDecrypt(key.getBytes(),
					CryptoUtil.hexAseDecrypt(key, qqshowsignature)));

			// 获取timestamp 时间戳 ; qqshowvip 红钻标志 1：红钻
			HashMap<String, String> unbindQQshowtokens = ParseString.parseTokenString(unbindQQshow);
			qqshowvip = unbindQQshowtokens.get("qqshowvip");

			qqtimestamp = unbindQQshowtokens.get("qqshow_timestamp");

		}

		// PrintWriter out = response.getWriter();

		try {
			if (!Verify.verifyOpenID(openid, timestamp, oauth_signature)) {
				// out.println("openid verify false!");
				logger.warn("OpenId verify false: openid:" + openid + "timestamp:" + timestamp + "oauth_signature:"
						+ oauth_signature);
			}
		} catch (InvalidKeyException e1) {
			e1.printStackTrace();
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}

		UserData userData = new UserData(request, response);
		String showName = "QQ秀用户";
		HashMap<String, String> userinfo;
		// 若为qqshow免登，避掉授权检查
		if (qqshowsignature == null || qqshowsignature.equals("")) {
			// 用授权的request token换取access token
			AccessToken token = new AccessToken();

			String oauth_token_secret = "";
			if (qqshowsignature != null && !qqshowsignature.equals("")) {

				// userData.writeRawValue("oauth_token_secret",
				// request.getParameter("oauth_token_secret"));
				oauth_token_secret = request.getParameter("oauth_token_secret");
			} else {

				oauth_token_secret = userData.readRawValue("oauth_token_secret");
			}
			// String oauth_token_secret = (String)
			// request.getSession().getAttribute("oauth_token_secret");
			String access_token = null;
			try {
				access_token = token.getAccessToken(oauth_token, oauth_token_secret, oauth_vericode);
			} catch (InvalidKeyException e1) {
				e1.printStackTrace();
			} catch (NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			}
			HashMap<String, String> tokens = ParseString.parseTokenString(access_token);
			// error
			if (tokens.get("error_code") != null) {
				// out.println(tokens.get("error_code"));
				logger.error("verify2 error_code:" + tokens.get("error_code"));
			}
			// 获取access token成功后也会返回用户的openid
			// 我们强烈建议第三方使用此openid
			// 检查返回的openid是否是合法id
			try {
				if (!Verify.verifyOpenID(tokens.get("openid"), tokens.get("timestamp"), tokens.get("oauth_signature"))) {
					logger.warn("OpenId verify2 false: openid:" + tokens.get("openid") + "timestamp:" + tokens.get("timestamp")
							+ "oauth_signature:" + tokens.get("oauth_signature"));
				}
			} catch (InvalidKeyException e1) {
				e1.printStackTrace();
			} catch (NoSuchAlgorithmException e1) {
				e1.printStackTrace();
			}
			// 将access token，openid保存!!
			oauth_token = tokens.get("oauth_token");
			oauth_token_secret = tokens.get("oauth_token_secret");
			openid = tokens.get("openid");
			InfoToken infotoken = new InfoToken();
			String info_xml = null;
			try {
				info_xml = infotoken.getInfo(oauth_token, oauth_token_secret, openid, "xml");
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InvalidKeyException e) {
				e.printStackTrace();
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			userinfo = null;
			try {
				userinfo = XMLHelper.getInstance().getInfo(info_xml);
			} catch (SAXException e) {
				e.printStackTrace();
			}
			showName = userinfo.get("nickname");
		}
		try {

			if (qqtimestamp != "" && qqtimestamp != null) {
				// 计算时间差
				Long timeNow = DateUtils.addMinutes(new Date(), 0).getTime();
				Long timeBetween = timeNow / 1000 - Integer.parseInt(qqtimestamp);

				// 判断是否时间是否合法
				// if(timeBetween<300){
				// 保存渠道编号
				if ("1".equals(qqshowvip)) {

					userData.setApplySource("qqrubymember");
				} else {
					userData.setApplySource("");
				}
				// }else{
				// logger.error("error: QQ红钻验证超时 ");
				// return "logout";
				// }
			} else {
				userData.setApplySource("");
			}

		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
		// 第三方处理用户绑定逻辑
		// 将openid与第三方的帐号做关联
		// String showName = new String(userinfo.get("nickname").getBytes(
		// "ISO-8859-1"), "UTF-8");

		trustLogin(openid, showName, null, "qqmember", showName);

		return "loginOK";
	}

	public String pcladyLogin() throws CoreException, Exception {
		String openid = null;
		String showName = null;
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		TreeMap<String, String> map = parseUrl(request.getQueryString(), "UTF-8");
		openid = map.get("openId");
		showName = map.get("name");
		pathparam = map.get("retURL");
		if (StringUtils.isBlank(pathparam) || "/".equals(pathparam)) {
			pathparam = ServerValue.getFrontHostname();
		} else if (!pathparam.startsWith("http://")) {
			pathparam = ServerValue.getFrontHostname() + pathparam;
		}
		// 超出30分钟
		if (Long.parseLong(map.get("time")) < DateUtils.addMinutes(new Date(), -30).getTime()) {
			logger.error("pclady error: 超出30分钟 " + map);
			return "logout";
		}
		String code = map.get("openId") + "|" + map.get("name") + "|" + map.get("time") + "|" + PCLADY_APP_KEY + "|"
				+ PCLADY_SECRET;
		// 验证码不合
		if (!map.get("sign").equalsIgnoreCase(BytesUtil.md5Signature(code))) {
			logger.error("pclady error: 验证码不合 " + map);
			return "logout";
		}
		trustLogin(openid + "@pclady", showName, null, "pcladymember", showName);
		return "loginOK";
	}

	private void trustLogin(String loginId, String name, String email, String apply_source, String showName)
			throws CoreException, Exception {
		member = memberService.getMemberByLoginId(loginId);
		if (null == member) {
			member = new Member();
			HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(
					ServletActionContext.HTTP_REQUEST);
			member.setLoginId(loginId);

			// 保存yoka用户的名称
			if ("yokamember".equals(apply_source)) {
				member.setName(showName);

			}
			// 保存qqname
			else if ("qqmember".equals(apply_source)) {
				if (name.length() > 20 && StringUtils.isNotBlank(name)) {
					member.setName(StringUtils.substring(name, 0, 16));
				} else {

					member.setName(name);
				}
			} else if ("sinamember".equals(apply_source)) {
				member.setName(name);
			} else if (loginId.length() > 20 && StringUtils.isNotBlank(name)) {
				member.setName(StringUtils.substring(name, 0, 16));
			}
			if (StringUtils.isNotBlank(email) && email.contains("@")) {
				member.setEmail(email);
			} else {
				member.setEmail("xx");
			}
			member.setRank("1");
			member.setStatus("00");
			member.setActiveDate(new Date());
			member.setPwd("xx");

			String host = request.getHeader("X-Forwarded-For");
			if (StringUtils.isBlank(host)) {
				host = request.getRemoteAddr();
			}
			member.setClientIp(StringUtils.isBlank(host) ? "" : host.length() > 100 ? host.substring(0, 100) : host);
			member.setApplySource(apply_source);
			String domainSrc = request.getServerName();
			member.setDomainSrc(domainSrc);
			member = memberService.save(member);
			memberService.newBalance(member);
			member = memberService.getMemberByLoginId(member.getLoginId());
		}
		autoLogin(member, showName);
	}

	public String yokalogin() throws CoreException, Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		pathparam = request.getParameter("redirect_url");
		String sid = request.getParameter("sid");
		String key = "yoka_&yaodian100";
		// Option option = JspUtil.menuOption("SystemValue", "yoka");
		// String key = option.getMemo1();
		String aes = new String(CryptoUtil.aesDecrypt(key.getBytes(), CryptoUtil.hexAseDecrypt(key, sid)));
		HashMap<String, String> yokaaes = ParseString.parseTokenString(aes);
		Long timestamp = Long.parseLong(yokaaes.get("timestamp")); // yoka传出的时间
		String userId = yokaaes.get("userId");// 会员编号
		String userName = yokaaes.get("userName");// 会员名称
		Date currentdate = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmm");
		Long time = Long.parseLong(formatter.format(currentdate));
		Long timeBetween = time - timestamp;

		// 判读是否验证超时
		// if (timeBetween > 5) {
		// logger.error("error: yoka验证超时 ");
		// return "logout";
		// }

		// 检查是否有此账号 或注册
		trustLogin(userId, userName, null, "yokamember", userName);

		return "loginOK";

	}

	// sina授权
	public void tosinalogin() throws IOException, InvalidKeyException, NoSuchAlgorithmException {
		if (StringUtils.isBlank(redirect_url)) {
			redirect_url = ServerValue.getFrontHostname();
		}
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);
		com.yaodian100.sina.weibo4j.http.RequestToken resToken = com.yaodian100.sina.examples.WebOAuth.request(redirect_url
				+ "/ecmall/sinaLogin.do");
		// com.yaodian100.sina.weibo4j.http.RequestToken resToken = weboauth
		// .request("http://yanling.yaodian100.com/ecmall/sinaLogin.do");
		if (resToken != null) {

			userData.writeRawValue("Token", resToken.getToken());
			userData.writeRawValue("TokenSecret", resToken.getTokenSecret());

			try {

				userData.getResponse().sendRedirect(resToken.getAuthenticationURL());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	// sina联合登录

	public String sinaLogin() throws CoreException, Exception {
		HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(
				ServletActionContext.HTTP_RESPONSE);
		UserData userData = new UserData(request, response);

		String oauth_verifier = request.getParameter("oauth_verifier");
		String oauth_token = request.getParameter("oauth_token");
		if (oauth_verifier != null) {
			String Token = userData.readRawValue("Token");
			String TokenSecret = userData.readRawValue("TokenSecret");
			if (Token != null && !"".equals(Token) && TokenSecret != null && !"".equals(TokenSecret)) {

				com.yaodian100.sina.weibo4j.http.AccessToken accessToken = com.yaodian100.sina.examples.WebOAuth
						.requstAccessToken(Token, TokenSecret, oauth_verifier);

				if (accessToken != null) {
					String[] args = { accessToken.getToken(), accessToken.getTokenSecret(), accessToken.getUserId() + "" };
					com.yaodian100.sina.weibo4j.Weibo weibo = new com.yaodian100.sina.weibo4j.Weibo();
					weibo.setToken(args[0], args[1]);
					try {
						User user = weibo.showUser(args[2]);
						trustLogin(String.valueOf(user.getId()), user.getName(), null, "sinamember", user.getName());
						return "loginOK";
					} catch (com.yaodian100.sina.weibo4j.WeiboException e) {
						e.printStackTrace();
					}
				} else {

					logger.error("访问令牌请求错误");
				}
			} else {
				logger.error("request token session error");
			}
		} else {
			logger.error("verifier String error");
		}
		return "logout";
	}

	public String getYid() {
		return yid;
	}

	public void setYid(String yid) {
		this.yid = yid;
	}

	public String getWid() {
		return wid;
	}

	public void setWid(String wid) {
		this.wid = wid;
	}

	public String getFbt() {
		return fbt;
	}

	public void setFbt(String fbt) {
		this.fbt = fbt;
	}

	public String getFrom() {
		return from;
	}

	public void setFrom(String from) {
		this.from = from;
	}

	public String getU_id() {
		return u_id;
	}

	public void setU_id(String uId) {
		u_id = uId;
	}

	public ChannelService getChannelService() {
		return channelService;
	}

	public void setChannelService(ChannelService channelService) {
		this.channelService = channelService;
	}

	public TemplateService getVelocityService() {
		return velocityService;
	}

	public void setVelocityService(TemplateService velocityService) {
		this.velocityService = velocityService;
	}

	public int getErrTimes() {
		return errTimes;
	}

	public void setErrTimes(int errTimes) {
		this.errTimes = errTimes;
	}

	public String getFanliKey() {
		return fanliKey;
	}

	public void setFanliKey(String fanliKey) {
		this.fanliKey = fanliKey;
	}

	public List<Announcement> getMemberMessageList() {
		return this.memberMessageList;
	}

	public void setMemberMessageList(List<Announcement> memberMessageList) {
		this.memberMessageList = memberMessageList;
	}

	public XunLeiServiceImpl getXunLeiServiceImpl() {
		return xunLeiServiceImpl;
	}

	public void setXunLeiServiceImpl(XunLeiServiceImpl xunLeiServiceImpl) {
		this.xunLeiServiceImpl = xunLeiServiceImpl;
	}

	public int getXerrTimes() {
		return xerrTimes;
	}

	public void setXerrTimes(int xerrTimes) {
		this.xerrTimes = xerrTimes;
	}

	public String getXloginID() {
		return xloginID;
	}

	public void setXloginID(String xloginID) {
		this.xloginID = xloginID;
	}

	public String getLimitMobileRegTimes() {
		return limitMobileRegTimes;
	}

	public String getMemberId() {
		return memberId;
	}

	public void setMemberId(String memberId) {
		this.memberId = memberId;
	}

	public String getSms() {
		return sms;
	}

	public void setSms(String sms) {
		this.sms = sms;
	}

	public String getMgmName() {
		return mgmName;
	}

	public void setMgmName(String mgmName) {
		this.mgmName = mgmName;
	}

	public String getShowMsg() {
		return showMsg;
	}

	public void setShowMsg(String showMsg) {
		this.showMsg = showMsg;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}

	public String getCompleteInfoBonus() {
		if (StringUtils.isBlank(completeInfoBonus)) {
			completeInfoBonus = menuService.get("SystemValue").getOptions().get("complete_info_bonus").getMemo1();
		}
		return completeInfoBonus;
	}

	public CouponItem getCpItem() {
		return cpItem;
	}

	public void setCpItem(CouponItem cpItem) {
		this.cpItem = cpItem;
	}

	public String getNumOrderCommet() {
		return numOrderCommet;
	}

	public void setNumOrderCommet(String numOrderCommet) {
		this.numOrderCommet = numOrderCommet;
	}

}